package com.zhuangfei.hpuhelper.view;

import com.bigkoo.pickerview.OptionsPickerView;
import com.hpu.bean.Course;
import com.hpu.bean.CourseListEntity;
import com.hpu.bean.Week;
import com.hpu.constants.HttpConstants;
import com.hpu.constants.ShareConstants;
import com.hpu.parser.CourseParser;
import com.hpu.parser.WeekParser;
import com.hpu.service.CourseService;
import com.hpu.service.LoginService;
import com.hpu.service.WeekService;
import com.hpu.tools.ShareTools;
import com.hpu.tools.TimeTools;
import com.zhuangfei.hpuhelper.tools.ActivityTools;
import com.zhuangfei.hpuhelper.tools.CourseTools;
import com.zhuangfei.hpuhelper.tools.DefaultHandler;
import com.zhuangfei.hpuhelper.tools.ReflectTools;
import com.zhuangfei.timetable.core.OnSubjectBindViewListener;
import com.zhuangfei.timetable.core.OnSubjectItemClickListener;
import com.zhuangfei.timetable.core.SubjectBean;
import com.zhuangfei.timetable.core.TimetableView;
import com.zhuangfei.toolkit.IntentToolkit;
import com.zhuangfei.toolkit.tools.ToastTools;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.lzf.serviceplatform.R;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

import android.Manifest;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主页面，主要负责4个Tab的初始化以及切换事件
 */
public class MainActivity extends AppCompatActivity implements OnSubjectItemClickListener,
        OnSubjectBindViewListener {

    private int cur_week = 1;

    private CourseService courseService;
    private LoginService loginService;
    private WeekService weekService;

    private TimetableView timetableView;
    private String term = "default_term";

    TextView titleTextView;
    TextView termTextView;

    String vpnPw="";

    ArrayList<String> optionsItems;

    final int SUCCESSCODE=1;

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_course);
        ButterKnife.bind(this);
        ActivityTools.setTransparent(this);
        inits();
        checkUpdate();
        loadData();
        shouldcheckPermission();
    }

    private void shouldcheckPermission() {
        PermissionGen.with(MainActivity.this)
                .addRequestCode(SUCCESSCODE)
                .permissions(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                )
                .request();
    }

    //申请权限结果的返回
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //权限申请成功
    @PermissionSuccess(requestCode = SUCCESSCODE)
    public void doSomething() {
        //在这个方法中做一些权限申请成功的事情

    }
    //申请失败
    @PermissionFail(requestCode =SUCCESSCODE)
    public void doFailSomething() {
        ToastTools.show(this,"权限不足，运行中可能会出现故障!");
    }


    private void inits() {
        timetableView = (TimetableView) findViewById(R.id.id_timetableView);
        titleTextView = findViewById(R.id.id_title);
        termTextView = findViewById(R.id.id_term);

        // 初始化帮助类
        courseService = new CourseService(handler, this);
        loginService = new LoginService(this, handler);
        weekService = new WeekService(this, handler);

        optionsItems=new ArrayList<>();
    }

    @Override
    public void onResume() {
        super.onResume();
        int check = (int) ShareTools.get(this, "course_update", 0);
        if (check == 1) {
            loadData();
            ShareTools.put(this, "course_update", 0);
        }
    }

    public void loadData() {
        CourseParser courseParser = new CourseParser();
        String courseString = (String) ShareTools.get(this, ShareConstants.STORE_COURSE, "");
        Log.i("string","string:"+courseString);
        if (courseString == null || courseString.equals("")) {
            courseService.getCourse();
            return;
        }

        List<Course> courseBeans = courseParser.parse(courseString);
        courseBeans=CourseTools.getHaveTimeList(this,courseBeans);

        if (courseBeans.size() > 0)
            term = courseBeans.get(0).getTerm();
        ShareTools.put(this, ShareConstants.STORE_TERM, term);

        List<Course> myCourseList = CourseTools.getCourseList(this, term);
        courseBeans.addAll(myCourseList);

        timetableView.setDataSource(transform(courseBeans))
                .setOnSubjectItemClickListener(this)
                .setOnSubjectBindViewListener(this)
                .bindTitleView(titleTextView)
                .setCurTerm(term)
                .setMax(true)
                .showTimetableView();
        timetableView.changeWeek(cur_week, true);
    }

    /**
     * 检查是否需要去自动校准
     */
    private void checkUpdate() {
        String start = ShareTools.get(this, ShareConstants.STORE_WEEK_STARTTIME, "").toString();
        if (start == null || start.equals("")) {
            weekService.getWeek();
        } else {
            cur_week = TimeTools.timeTransfrom(start);
            timetableView.changeWeek(cur_week, true);
        }
    }

    /**
     * 获取到校准的时间后更新
     *
     * @param string
     */
    protected void handleWeek(String string) {
        WeekParser weekParser = new WeekParser();
        Week week = weekParser.parse(string);
        if (week != null) {
            ShareTools.put(this, ShareConstants.STORE_WEEK_STARTTIME, week.getStartTime());
            cur_week = TimeTools.timeTransfrom(week.getStartTime());

            timetableView.changeWeek(cur_week, true);
        }

    }

    public List<SubjectBean> transform(List<Course> courses) {
        List<SubjectBean> subjectBeans = new ArrayList<>();
        Map<String, Integer> colorMap = new HashMap<>();
        int colorCount = 1;

        for (int i = 0; i < courses.size(); i++) {
            Course course = courses.get(i);
            int color;
            if (colorMap.containsKey(course.getName())) {
                color = colorMap.get(course.getName());
            } else {
                colorMap.put(course.getName(), colorCount);
                color = colorCount;
                colorCount++;
            }
            subjectBeans.add(new SubjectBean(course.getName(), course.getRoom(), course.getTeacher(), course.getWeekList(),
                    course.getStart(), course.getStep(), course.getDay(), color, course.getTime()));
        }
        return subjectBeans;
    }

    DefaultHandler handler = new DefaultHandler(MyApplication.getInstance()) {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                // 获取课程成功
                case HttpConstants.QUERY_COURSE_SUCCESS:
                    ShareTools.put(MainActivity.this, ShareConstants.STORE_COURSE, msg.obj.toString());
                    loadData();

                    break;

                // 校准时间成功
                case HttpConstants.QUERY_WEEK_SUCCESS:
                    handleWeek(msg.obj.toString());
                    break;

                case HttpConstants.VPN_TOOLONG:
                    if(handler.isIgnoreVpnExpired()){
                        break;
                    }
                    loginService.login(ShareTools.get(MainActivity.this, ShareConstants.STORE_USER, "").toString(),
                            ShareTools.get(MainActivity.this, ShareConstants.STORE_PASSWORD1, "").toString(),
                            ShareTools.get(MainActivity.this, ShareConstants.STORE_PASSWORD2, "").toString());
                    break;

                // 登录成功
                case HttpConstants.LOGIN_SUCCESS:
                    ShareTools.put(MainActivity.this, ShareConstants.STORE_LOGINCOOKIE, (String) msg.obj);
                    courseService.getCourse();
                    break;
            }
        }

        ;
    };

    @Override
    public void onItemClick(View v, List<SubjectBean> subjectList) {
        List<Course> courses = new ArrayList<>();

        for (int i = 0; i < subjectList.size(); i++) {
            SubjectBean subjectBean = subjectList.get(i);

            courses.add(new Course(term, subjectBean.getName(), subjectBean.getRoom(), subjectBean.getTeacher(), subjectBean
                    .getWeekList(), subjectBean.getStart(), subjectBean.getStep(), subjectBean.getDay(), subjectBean
                    .getColorRandom(), subjectBean.getTime()));
        }

        CourseListEntity courseListEntity = new CourseListEntity(courses);
        ActivityTools.toActivityAnimByExtras(MainActivity.this, CourseDetailActivity.class, ReflectTools.EXTRAS_COURSE,
                courseListEntity);
    }

    public void onRightClick(View v) {
        PopupMenu popup = new PopupMenu(MainActivity.this, v);
        popup.getMenuInflater().inflate(R.menu.popmenu_course, popup.getMenu());

        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.top1:
                        weekService.getWeek();
                        courseService.getCourse();
                        break;
                    case R.id.top2:
                        ActivityTools.toActivity(MainActivity.this, NoTimeClassActivity.class);

                        break;
                    case R.id.top3:
                        ActivityTools.toActivity(MainActivity.this, CourseManagerActivity.class);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

        popup.show();
    }

    @Override
    public void onBindTitleView(TextView titleTextView, int curWeek, String curTerm, List<SubjectBean> subjectBeans) {
        titleTextView.setText("第" + curWeek + "周");
    }

    @OnClick(R.id.id_main_menu)
    public void toMenuActivity() {
        ActivityTools.toActivity(MainActivity.this, MenuActivity.class);
    }

    @OnClick(R.id.id_title)
    public void onWeekTextViewClick(){
        optionsItems.clear();
        for(int i=1;i<=20;i++){
            if(cur_week==i){
                if(cur_week!=timetableView.getCurWeek()){
                    optionsItems.add("第"+i+"周(非本周)");
                }else{
                    optionsItems.add("第"+i+"周(当前周)");
                }
            }
            else{
                optionsItems.add("第"+i+"周");
            }
        }

        if(cur_week<=0) cur_week=1;
        if(cur_week>20) cur_week=20;

        //条件选择器
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                cur_week=options1+1;
                titleTextView.setText("第"+cur_week+"周");
                if(cur_week==timetableView.getCurWeek()){
                    termTextView.setText("本周");
                }else{
                    termTextView.setText("非本周");
                    timetableView.changeWeek(cur_week,false);
                }

            }
        }).setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setTitleText("周次切换")//标题
                .setSelectOptions(cur_week-1)
                .build();

        pvOptions.setPicker(optionsItems);
        pvOptions.show();
    }

    @OnClick(R.id.id_term)
    public void onTermTextViewClick(){
        if(termTextView.getText()!=null){
            if(termTextView.getText().toString().equals("本周")){
                ToastTools.show(this,"当前学期:"+term+"\n当前周次:"+cur_week);
            }else{
                timetableView.changeWeek(timetableView.getCurWeek(),true);
                termTextView.setText("本周");
                cur_week=timetableView.getCurWeek();
                ToastTools.show(this,"已恢复周次..");

            }
        }
    }

    Handler exitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            exitHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }
}
